package top.carrotguo.weibo.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;
import com.sina.weibo.sdk.auth.AccessTokenKeeper;

import java.sql.RowId;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindInt;
import butterknife.BindView;
import butterknife.OnClick;
import top.carrotguo.weibo.R;
import top.carrotguo.weibo.adapter.StatusGridImgsAdapter;
import top.carrotguo.weibo.adapter.StringAdapter;
import top.carrotguo.weibo.bean.CommentListBean;
import top.carrotguo.weibo.bean.HomeTimeLine;
import top.carrotguo.weibo.contract.HomeDetailContract;
import top.carrotguo.weibo.presenter.HomeDetailPresenter;
import top.carrotguo.weibo.retrofit.callback.ErrorInfo;
import top.carrotguo.weibo.ui.base.MVPBaseActivity;
import top.carrotguo.weibo.utils.DateUtils;
import top.carrotguo.weibo.utils.StringUtils;
import top.carrotguo.weibo.utils.TitlebarBuilder;
import top.carrotguo.weibo.utils.ToastUtils;
import top.carrotguo.weibo.widget.ObservableScrollView;
import top.carrotguo.weibo.widget.WrapHeightGridView;

public class HomeDetailActivity extends MVPBaseActivity<HomeDetailContract.View,HomeDetailPresenter>
    implements HomeDetailContract.View,ObservableScrollView.OnObservalbleScrollListener {

    @BindView(R.id.fl_comment_container)
    FrameLayout flCommentContainer;
    @BindView(R.id.scrollView)
    ObservableScrollView scrollView;
    @BindView(R.id.rg_controll_tool)
    RadioGroup rgTools;
    //存放工具类的外层布局
    @BindView(R.id.ll_out)
    LinearLayout llOut;
    //存放工具类的内层布局
    @BindView(R.id.ll_in)
    LinearLayout llIn;
    @BindView(R.id.root)
    LinearLayout llRoot;
    /*头像*/
    @BindView(R.id.iv_head)
    ImageView ivHead;
    /*用户名*/
    @BindView(R.id.tv_name)
    TextView tvName;
    /*微博来源*/
    @BindView(R.id.tv_res)
    TextView tvRes;
    /*装载九宫图的gridview*/
    @BindView(R.id.gv_pic)
    WrapHeightGridView gvPics;
    /*微博内容*/
    @BindView(R.id.tv_text)
    TextView tvText;
    /*来自的文字字样，当没有微博来源字段时，此字样要隐藏*/
    @BindView(R.id.tv_fromtext)
    TextView tvFromText;
    /*单张图片的微博*/
    @BindView(R.id.iv_pic)
    ImageView ivPic;
    /*包裹整个转发微博(转发)*/
    @BindView(R.id.include_retweet)
    View llRetweet;
    /*原微博的作者(转发)*/
    @BindView(R.id.tv_retweet_name_and_content)
    TextView tvRetweetContent;
    /*原微博的单张图片（转发）*/
    @BindView(R.id.iv_retween_pic)
    ImageView ivRetweetPic;
    /*装载原微博的九宫格（转发）*/
    @BindView(R.id.wgv_retween_pics)
    WrapHeightGridView wgvRetweetPics;
    /*微博创建时间*/
    @BindView(R.id.tv_create_at)
    TextView tvCreateAt;
    /*微博转发按钮*/
    @BindView(R.id.rb_retweet)
    RadioButton rbRetweet;
    /*微博点赞按钮*/
    @BindView(R.id.rb_like)
    RadioButton rbLike;
    /*微博评论按钮*/
    @BindView(R.id.rb_comment)
    RadioButton rbComment;
    /*微博的数据*/
    private HomeTimeLine.UsersBean data;

    private int mToolHeight;
    //传微博对象
    public static final String BLOG_DATA = "BLOG_DATA";
    //请求跳转到发表评论的activity
    public static final int REQ_SEND_COMMENT = 1;
    private CommentFragment commentFragment;
    public static final String SCROLL = "SCROLL";
    private boolean scrollToComment = false;

    @Override
    protected void initView() {
        super.initView();
        initTitle();
        initData();
        //设置scrollview的滑动监听
        scrollView.setonObservalbleScrollListener(this);
    }

    private void initTitle() {
        new TitlebarBuilder(mContext)
                .setLeftIcon(R.drawable.back_black)
                .setCenterTitle("微博正文")
                .setLeftIconClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onBackPressed();
                    }
                });
    }

    private void initData(){
        //加载微博内容
        initBlog();
        //滚动到评论位置
        if (scrollToComment) {
            scrollView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    scrollView.smoothScrollTo(0,mToolHeight);
                }
            },500);
        }

        //加载评论
        initComment();
    }

    /**
     * 加载微博内容
     */
    private void initBlog(){
        if (data != null) {
            //用户名
            String userName = data.getUser().getName();
            tvName.setText(userName+"");

            Logger.e("id：："+data.getUser().getId());
            //来自
            String res = data.getSource();
            Pattern pattern = Pattern.compile("<[^>]+>",Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(res);
            res = matcher.replaceAll("");
            tvRes.setText(res+"");
            tvFromText.setVisibility(TextUtils.isEmpty(res)?View.GONE:View.VISIBLE);

            //头像
            String headUrl = data.getUser().getProfile_image_url();
            Glide.with(mContext).load(headUrl).into(ivHead);

            //设置正文内容
            tvText.setText(StringUtils.getContentText(mContext,tvText,data.getText()));

            //设置发布时间
            tvCreateAt.setText(DateUtils.getShortTime(data.getCreated_at()));

            //设置九宫格
            ArrayList<HomeTimeLine.UsersBean.Pic> pics = data.getPicUrls();
            if (pics != null && pics.size()>1) {
                //显示九宫格
                gvPics.setVisibility(View.VISIBLE);
                ivPic.setVisibility(View.GONE);
                StatusGridImgsAdapter imageAdapter = new StatusGridImgsAdapter(mContext,pics);
                gvPics.setAdapter(imageAdapter);
            } else if (pics != null && pics.size() == 1) {
                //显示单张图片
                gvPics.setVisibility(View.GONE);
                ivPic.setVisibility(View.VISIBLE);
                Glide.with(mContext)
                        .load(data.getPicUrls().get(0).getThumbnail_pic())
                        .into(ivPic);
                //statusViewHolder.ivPic.measure(0,0);
            } else {
                //隐藏九宫格
                gvPics.setVisibility(View.GONE);
                ivPic.setVisibility(View.GONE);
            }

            //设置转发
            HomeTimeLine.UsersBean retweet = data.getRetweeted_status();
            if (retweet != null) {
                //设置转发内容和用户
                llRetweet.setVisibility(View.VISIBLE);
                tvRetweetContent
                        .setText(StringUtils.getContentText(mContext,
                                tvRetweetContent,
                                "@"+retweet.getUser().getName()+":"+retweet.getText()));

                //设置转发图片
                ArrayList<HomeTimeLine.UsersBean.Pic> retweetPics = retweet.getPicUrls();
                if (retweetPics != null && retweetPics.size()>1) {
                    //显示多张图片效果
                    ivRetweetPic.setVisibility(View.GONE);
                    wgvRetweetPics.setVisibility(View.VISIBLE);
                    StatusGridImgsAdapter adapter = new StatusGridImgsAdapter(mContext,retweetPics);
                    wgvRetweetPics.setAdapter(adapter);
                } else if (retweetPics != null && retweetPics.size() == 1) {
                    //显示单张图片效果
                    wgvRetweetPics.setVisibility(View.GONE);
                    ivRetweetPic.setVisibility(View.VISIBLE);
                    Glide.with(mContext)
                            .load(retweetPics.get(0).getThumbnail_pic())
                            .into(ivRetweetPic);
                } else {
                    //隐藏图片
                    ivRetweetPic.setVisibility(View.GONE);
                    wgvRetweetPics.setVisibility(View.GONE);
                }
            } else {
                llRetweet.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 加载评论
     */
    private void initComment(){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        commentFragment = CommentFragment.newInstance(data.getId());
        transaction.replace(R.id.fl_comment_container, commentFragment);
        transaction.commit();

        scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView nestedScrollView, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY == nestedScrollView.getChildAt(0).getMeasuredHeight() - nestedScrollView.getMeasuredHeight()) {
                    commentFragment.onLoadMore();
                }
            }
        });
    }


    /**
     * 加载完全部布局，window获得焦点时会调用此方法，此时可保证所有控件绘制完成
     * @param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        //获取内层工具栏顶部距离父控件顶部的距离，当nestedScrollView在竖直方向的偏移距离等于或超过此距离时，将工具栏移到外层布局
        mToolHeight = llIn.getTop();
    }

    @Override
    public HomeDetailPresenter createPresenter() {
        return new HomeDetailPresenter();
    }

    @Override
    public int provideContentViewId() {
        return R.layout.activity_detail;
    }

    @Override
    public Bundle getBundleExtras(Bundle bundle) {
        if (bundle != null) {
            data = (HomeTimeLine.UsersBean) bundle.getSerializable(BLOG_DATA);
            scrollToComment = bundle.getBoolean(SCROLL,false);
            Logger.e("微博id："+data.getId());
            Logger.e("token："+AccessTokenKeeper.readAccessToken(mContext));
        }
        return null;
    }

    @OnClick({R.id.rb_comment,R.id.rb_like,R.id.rb_retweet})
    void onGenderSelected(RadioButton radio){
        boolean checked = radio.isChecked();
        if (checked) {
            switch (radio.getId()) {
                case R.id.rb_retweet : {
                    showToast("转发");
                    break;
                }
                case R.id.rb_comment : {
                    showToast("评论");
                    break;
                }
                case R.id.rb_like : {
                    showToast("点赞");
                    break;
                }
            }
        }

    }

    /**
     * 用于监听当前scrollview相对于屏幕的偏移量
     * @param l
     * @param t
     * @param oldl
     * @param oldt
     */
    @Override
    public void onObservalbleScrollChanged(int l, int t, int oldl, int oldt) {
        if (t>=mToolHeight) {
            if (rgTools.getParent() != llOut) {
                //将工具栏从内层布局移除，外层布局添加工具栏
                llIn.removeView(rgTools);
                llOut.addView(rgTools);
            }
        } else {
            //将工具栏从外层布局移除，内层布局添加工具栏
            if (rgTools.getParent() != llIn) {
                llOut.removeView(rgTools);
                llIn.addView(rgTools);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQ_SEND_COMMENT:{
                //由发表评论页面返回的内容
                if (resultCode == CommentActivity.RESULT_SEND) {
                    //发表成功|失败
                    boolean isSuccess = data.getBooleanExtra(CommentActivity.SEND_SUCCESSED,false);
                    if (isSuccess) {
                        //发表成功  刷新数据
                        if (commentFragment != null) {
                            //重新加载评论列表的数据
                            commentFragment.refreshList();
                            //回到列表顶部
                            scrollView.scrollTo(0,mToolHeight);
                        }
                    }
                }
                break;
            }
        }
    }

    @OnClick(R.id.ll_retweet)
    public void clickRetweet(View view){
        showToast("转发");
    }

    @OnClick(R.id.ll_comment)
    public void clickComment(View view) {
        showToast("评论");
        Bundle bundle = new Bundle();
        bundle.putString(CommentActivity.ID,data.getId());
        readyGoForResult(CommentActivity.class,bundle,REQ_SEND_COMMENT);
    }

    @OnClick(R.id.ll_like)
    public void clickLike(View view){
        showToast("点赞");
    }
}
